package com.ihcy.base.config;

import com.ihcy.base.core.ExceptionEnum;
import com.ihcy.base.core.Result;
import com.ihcy.base.core.ServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = ServerException.class)
    @ResponseBody
    public Result<Void> serviceExceptionHandler(HttpServletRequest request, ServerException e) {
        logger.error("请求{}业务异常! 异常描述: {}", request.getRequestURI(), e.getMessage());
        return Result.fail(e.getErrorCode(), e.getMessage());
    }

    @ExceptionHandler(value = HttpMessageConversionException.class)
    @ResponseBody
    public Result<Void> httpMessageNotReadableExceptionHandler(HttpServletRequest request, HttpMessageConversionException e){
        logger.error("请求{}, 信息有误 。原因是:", request.getRequestURI(), e);
        return Result.fail(ExceptionEnum.BODY_NOT_MATCH,e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Void> exceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("请求 {} 异常。原因是:", request.getRequestURI(), e);
        return Result.fail(ExceptionEnum.INTERNAL_SERVER_ERROR);
    }

}
